package com.yixing.tech.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.yixing.tech.common.base.BusinessException;
import com.yixing.tech.common.enums.ErrCode;
import com.yixing.tech.common.vo.s3.LogInfo;
import com.yixing.tech.common.vo.s3.TenantVO;
import com.yixing.tech.common.vo.s3.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yixing tech
 * at 2022/10/15
 * describe：
 */
@Slf4j
@Component
public class FSApiUtil {


    private static FSApiUtil self;

    @Resource
    private MongoTemplate mongoTemplate;

    private static String tokenHttp = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal";
    public static String sendMsgHttp = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=open_id";
    public static String openIdHttp = "https://open.feishu.cn/open-apis/contact/v3/users/batch_get_id";


    @PostConstruct
    private void init() {
        self = this;
    }

    /**
     * 获取token
     *
     * @param appId
     * @param secret
     * @return
     * @throws BusinessException
     */
    public static String getToken(String appId, String secret) throws BusinessException {
        if (org.apache.commons.lang3.StringUtils.isBlank(appId) || org.apache.commons.lang3.StringUtils.isBlank(secret))
            throw new BusinessException(ErrCode.PARAMETER_ERROR);
        RestTemplate restTemplate = new RestTemplate();
        Map map = new HashMap(2);
        map.put("app_id", appId);
        map.put("app_secret", secret);
        String responseStr = restTemplate.postForObject(tokenHttp, map, String.class);
        JSONObject response = JSONObject.parseObject(responseStr);
        if (response.getInteger("code") == 0) {
            return response.getString("tenant_access_token");
        } else {
            throw new BusinessException(ErrCode.UNAUTHORIZED);
        }
    }


    public static void sendMsg(String tenantId, List<String> userIds, String content) throws BusinessException {
        log.info("------sendWxMsg------:" + Arrays.toString(userIds.toArray()));
        TenantVO tenant = self.mongoTemplate.findById(new ObjectId(tenantId), TenantVO.class, "tenant");
        if (tenant == null || org.apache.commons.lang3.StringUtils.isBlank(tenant.getAppletAppId()))
            throw new BusinessException(ErrCode.PARAMETER_ERROR);
        String token = FSApiUtil.getToken(tenant.getAppletAppId(), tenant.getAppletSecret());
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + token);
        Map<String, Object> data = new HashMap<>(4);
        data.put("content", content);
        data.put("msg_type", "interactive");
        HttpEntity httpEntity = new HttpEntity<>(data, headers);
        for (String userId : userIds) {
            UserVO user = self.mongoTemplate.findById(new ObjectId(userId), UserVO.class, "user");
            if (user == null) continue;
            String openId = user.getOpenId();
            data.put("receive_id", openId);
            String responseStr = restTemplate.postForObject(FSApiUtil.sendMsgHttp, httpEntity, String.class);
            JSONObject response = JSONObject.parseObject(responseStr);
            if (response.getInteger("code") == 0) {
                LogInfo logInfo = new LogInfo();
                logInfo.setTenantId(tenantId);
                logInfo.setPath("/sendFSMsg");
                logInfo.setMethod("post");
                logInfo.setName("消息推送");
                logInfo.setContent(content);
                self.mongoTemplate.save(logInfo);
            } else {
                log.error(responseStr);
                throw new BusinessException(-1, response.getInteger("msg"));
            }
        }
    }


    /**
     * 获取飞书openId
     *
     * @return
     * @throws BusinessException
     */
    public static String getOpenId(String tenantId, String userId) throws BusinessException {
        UserVO user = self.mongoTemplate.findById(new ObjectId(userId), UserVO.class, "user");
        if (!ObjectUtils.isEmpty(user.getOpenId())) return user.getOpenId();
        TenantVO tenant = self.mongoTemplate.findById(new ObjectId(tenantId), TenantVO.class, "tenant");
        if (tenant == null || org.apache.commons.lang3.StringUtils.isBlank(tenant.getAppletAppId()))
            throw new BusinessException(ErrCode.PARAMETER_ERROR);
        String token = FSApiUtil.getToken(tenant.getAppletAppId(), tenant.getAppletSecret());
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + token);
        Map<String, Object> data = new HashMap<>(4);
        data.put("mobiles", Arrays.asList(user.getPhone()));
        HttpEntity httpEntity = new HttpEntity<>(data, headers);
        String responseStr = restTemplate.postForObject(openIdHttp, httpEntity, String.class);
        JSONObject response = JSONObject.parseObject(responseStr);
        if (response.getInteger("code") == 0) {
            String openId = response.getJSONObject("data").getJSONArray("user_list").getJSONObject(0).getString("user_id");
            return openId;
        } else {
            log.error(responseStr);
            throw new BusinessException(-1, response.getInteger("msg"));
        }
    }


}
